package gins

import (
	"fmt"
	gin "github.com/gin-gonic/gin"
	gf "github.com/gogf/gf/frame/g"
	"github.com/micro/go-micro/v2/web"
	"log"
	"time"
)

type Server struct {
	ginEngine *gin.Engine
}

func New() *Server {
	s := new(Server)
	s.ginEngine = gin.Default()
	return s
}

func (s *Server) GetGinEngine() *gin.Engine {
	return s.ginEngine
}

// 启动Web服务器
func (s *Server) Run() {
	// ----------- 协程方式启动，不阻塞当前线程 ---------------
	go s.MicroServerRun()

	// ------------ 延时启动，等待go-micro服务启动完成 ---------------
	time.Sleep(3 * time.Second)
	s.WebServerRun()
}

func (s *Server) WebServerRun() {
	ss := gf.Server()
	ss.Run()
}

// 启动GoMicro服务
func (s *Server) MicroServerRun() {
	serverName := gf.Cfg().GetString("micro.Name")
	serverPort := gf.Cfg().GetString("micro.Address")

	engine := s.ginEngine
	service := web.NewService(
		web.Name(serverName),
		web.Address(fmt.Sprintf("%v", serverPort)),
		web.Handler(engine),
	)
	service.Init()

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
